package org.com.gamemall.Utity;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class RedisLock implements ILock {
    private static final String GET_LOCK_TTL = String.valueOf(15L);

    public RedisLock(String lockName, StringRedisTemplate stringRedisTemplate) {
        this.lockName = lockName;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    private StringRedisTemplate stringRedisTemplate;
    private String lockName;

    @Override
    public Boolean tryLock() {
        String threadId = UUID.randomUUID() + Thread.currentThread().getName();

        Boolean success = stringRedisTemplate.opsForValue()
                .setIfAbsent(lockName, threadId, Long.parseLong(GET_LOCK_TTL), TimeUnit.MINUTES);
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unLock() {
        String threadId = UUID.randomUUID().toString() + Thread.currentThread().getName();
        stringRedisTemplate.opsForValue().get(lockName);
        if (threadId.equals(threadId)) {
            stringRedisTemplate.delete(lockName);
        }
    }
}
